package com.resttest.ljs.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
@Component
public class RabbitSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //发送 通用方法
    public String sendSomething(String exchange , String routingKey , String msg) throws Exception {
        if(msg == null){
            throw new Exception("队列消息不能为null");
        }
        Message send = new Message(msg.getBytes(StandardCharsets.UTF_8),new MessageProperties());
        CorrelationData correlationData = new CorrelationData(routingKey + UUID.randomUUID());
        Message receive = rabbitTemplate.sendAndReceive(exchange,routingKey,send,correlationData);
        if(receive == null || receive.getBody() == null){
            throw  new Exception("队列消息返回为null");
        }
        return new String(receive.getBody(),StandardCharsets.UTF_8);
    }
}
